package cn.iocoder.yudao.module.famous.doctor.service.forum;

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.famous.doctor.controller.admin.forumRecord.vo.FamForumRecordExportReqVO;
import cn.iocoder.yudao.module.famous.doctor.controller.admin.reply.Enum.ReplyEnum;
import cn.iocoder.yudao.module.famous.doctor.controller.admin.reply.vo.FamReplyExportReqVO;
import cn.iocoder.yudao.module.famous.doctor.convert.forumRecord.FamForumRecordConvert;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.forumRecord.FamForumRecordDO;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.reply.FamReplyDO;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.forumRecord.FamForumRecordMapper;
import cn.iocoder.yudao.module.famous.doctor.service.forumRecord.FamForumRecordServiceImpl;
import cn.iocoder.yudao.module.famous.doctor.service.reply.FamReplyServiceImpl;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.vo.MemberUserParamDO;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.famous.doctor.controller.admin.forum.vo.*;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.forum.FamForumDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.famous.doctor.convert.forum.FamForumConvert;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.forum.FamForumMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.famous.doctor.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 论坛表 Service 实现类
 *
 * @author Test1
 */
@Service
@Validated
@Slf4j
public class FamForumServiceImpl implements FamForumService {

    @Resource
    private FamForumMapper famForumMapper;
    @Resource
    private FamForumRecordServiceImpl famForumRecordService;
    @Resource
    private FamReplyServiceImpl famReplyService;
    @Resource
    private FamForumRecordMapper famForumRecordMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private MemberUserService memberUserService;


    @Override
    public Long createFamForum(FamForumCreateReqVO createReqVO) {
        // 插入
        FamForumDO famForum = FamForumConvert.INSTANCE.convert(createReqVO);
        famForumMapper.insert(famForum);
        // 返回
        return famForum.getId();
    }

    @Override
    public void updateFamForum(FamForumUpdateReqVO updateReqVO) {
        // 校验存在
        validateFamForumExists(updateReqVO.getId());
        // 更新
        FamForumDO updateObj = FamForumConvert.INSTANCE.convert(updateReqVO);
        famForumMapper.updateById(updateObj);
    }

    @Override
    public void deleteFamForum(Long id) {
        // 校验存在
        validateFamForumExists(id);
        // 删除
        famForumMapper.deleteById(id);
    }

    private void validateFamForumExists(Long id) {
        if (famForumMapper.selectById(id) == null) {
            throw exception(FAM_FORUM_NOT_EXISTS);
        }
    }

    @Override
    public FamForumDO getFamForum(Long id) {
        return famForumMapper.selectById(id);
    }

    @Override
    public List<FamForumDO> getFamForumList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return famForumMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<FamForumDO> getFamForumPage(FamForumPageReqVO pageReqVO) {
        return famForumMapper.selectPage(pageReqVO);
    }

    @Override
    public List<FamForumDO> getFamForumList(FamForumExportReqVO exportReqVO) {
        return famForumMapper.selectList(exportReqVO);
    }

    @Override
    public PageResult<FamForumRespTwoVO> getFamForumPageParticulars(FamForumPageReqVO pageVO) {
        PageResult<FamForumRespTwoVO> famForumRespVOPageResult = FamForumConvert.INSTANCE.convertPage2(famForumMapper.selectPageParticulars(pageVO));
        dataProcessing(famForumRespVOPageResult.getList());

        return famForumRespVOPageResult;
    }

    @Override
    public List<FamForumRespTwoVO> getFamForumRandomParticulars(FamForumPageReqVO pageVO) {
        List<FamForumDO> famForumDOS = famForumMapper.selectList(pageVO);
        List<FamForumRespTwoVO> famForumRespTwoVO=FamForumConvert.INSTANCE.convertFamForumRespTwoVO(famForumDOS);
        dataProcessing(famForumRespTwoVO);
        return famForumRespTwoVO;
    }


    public void dataProcessing(List<FamForumRespTwoVO> pageVO) {
        //获取【回复】记录表所有信息
        List<FamReplyDO> famReplyList = famReplyService.getFamReplyList(new FamReplyExportReqVO());

        pageVO.forEach(famForumRespVO -> {
            //查询论坛回复量
            famForumRespVO.setReplyCount(famReplyList.stream().filter(famReplyDO -> famReplyDO.getForumId().equals(famForumRespVO.getId())).count());
            //查询谈论点赞数量
            famForumRespVO.setUpvoteCount(getCollectCount(famForumRespVO.getId(), ReplyEnum.REPLY_UPVOTE));
            //查询该谈论  用户是否收藏量
            famForumRespVO.setIsUpvote(getCollectCount(null, famForumRespVO.getId(), ReplyEnum.REPLY_UPVOTE));
            //查询谈论收藏量
            famForumRespVO.setCollectCount(getCollectCount(famForumRespVO.getId(), ReplyEnum.REPLY_COLLECT));
            //查询该谈论  用户是否收藏量
            famForumRespVO.setIsCollect(getCollectCount(null, famForumRespVO.getId(), ReplyEnum.REPLY_COLLECT));
            MemberUserDO user = memberUserService.getUser(Long.valueOf(famForumRespVO.getCreator()));
            if (user!=null) {
                MemberUserParamDO memberUserParamDO = new MemberUserParamDO();
                BeanUtils.copyProperties(user,memberUserParamDO);
                famForumRespVO.setPublishUserMessage(memberUserParamDO);
            }
        });
    }
    /**
     * 获取论坛 点赞/收藏 数量
     *
     * @param forumId    论谈id标识
     * @param replyState 类型 1点赞 2收藏
     * @return
     */
    public Long getCollectCount(Long forumId, ReplyEnum replyState) {
        Long result=0L;
//        FamForumRecordExportReqVO famForumRecordExportReqVO = new FamForumRecordExportReqVO()
//                .setForumId(forumId)
//                .setState(replyState.getValue());
//        List<FamForumRecordDO> famForumRecordList = famForumRecordService.getFamForumRecordList2(famForumRecordExportReqVO, false);

        String key = "fam_forum_record"+ ":" +replyState.getValue();
        List<FamForumRecordDO>  famForumRecordList = redisTemplate.opsForHash().values(key);
        long count = famForumRecordList.stream()
                .filter(famForumRecordDO ->
                        famForumRecordDO.getForumId() == forumId && famForumRecordDO.getThumbsupId() == null).count();
        if (count>0) {
            result=1L;
        }
        return result;
    }

    /**
     * 获取登录用户 点赞/收藏的内容
     *
     * @param thumbsupId   论谈回复id(区分回复途径 空值代表对论坛的回复  有值是对论坛下回复id的回复)
     * @param forumId      论谈id标识
     * @param replyState   类型 1点赞 2收藏
     * @return 1已点赞/收藏 2 未点赞/收藏
     */
    public Long getCollectCount(Long thumbsupId, Long forumId, ReplyEnum replyState) {
//        FamForumRecordExportReqVO famForumRecordExportReqVO = new FamForumRecordExportReqVO()
//                .setForumId(forumId)
//                .setState(replyState.getValue())
//                .setThumbsupId(thumbsupId)
//                ;
//        boolean empty = famForumRecordService.getFamForumRecordList2(famForumRecordExportReqVO, true).isEmpty();

        String key = "fam_forum_record"+ ":" +replyState.getValue();
        String hashkey = getLoginUserId()+"_"+ forumId  +"_"+ thumbsupId;
        Boolean empty = redisTemplate.opsForHash().hasKey(key, hashkey);
        return (long) (!empty == true ? 0 : 1);
    }


    @Override
    public IPage<FamForumiIformRespVO> getFamForumInformPage(FamForumInformPageReqVO pageVO) {
        List<FamForumiIformRespVO>  famForumiIformRespVOS =null ;
        if (pageVO.getReplyState()!=null) {
            if (pageVO.getReplyState()==1 || pageVO.getReplyState()==2) {
                String key = "fam_forum_record"+ ":" +pageVO.getReplyState();
                List<FamForumRecordDO> forumRecordDOS = redisTemplate.opsForHash().values(key);
                List<Long> selectlisted=famForumMapper.selectlistByuserid(getLoginUserId());
                List<FamForumRecordDO> filteredRecords =null;
                if (pageVO.getReplyState()==1 ){
                    List<FamForumRecordDO> byuserid=famForumRecordMapper.selectlistByuserid(getLoginUserId());
                    filteredRecords = forumRecordDOS.stream()
                            .filter(record -> selectlisted.contains(record.getForumId()) || byuserid.contains(record.getThumbsupId()))
                            .collect(Collectors.toList());
                }else {
                    filteredRecords = forumRecordDOS.stream()
                            .filter(record -> selectlisted.contains(record.getForumId())&&record.getThumbsupId()==null)
                            .collect(Collectors.toList());
                }
                famForumiIformRespVOS =FamForumRecordConvert.INSTANCE.convertForumiIform(filteredRecords);
                if(famForumiIformRespVOS!=null) {
                    famForumiIformRespVOS.forEach(famForumiIformRespVO -> {
                        if(famForumiIformRespVO.getCreator()!=null) {
                            MemberUserDO memberUserDO = memberUserService.selectById(famForumiIformRespVO.getCreator());
                            if (memberUserDO!=null) {
                                famForumiIformRespVO.setNickName(memberUserDO.getNickname());
                                famForumiIformRespVO.setHeadPortrait(memberUserDO.getAvatar());
                            }
                        }
                    });
                }

            }else if (pageVO.getReplyState()==3) {
                //回复
                famForumiIformRespVOS= famForumRecordMapper.selecttalkByuserid(getLoginUserId());
                if(famForumiIformRespVOS!=null) {
                    famForumiIformRespVOS.forEach(famForumiIformRespVO -> {
                        if(famForumiIformRespVO.getReplyUser()!=null) {
                            MemberUserDO memberUserDO = memberUserService.selectById(famForumiIformRespVO.getReplyUser());
                            if (memberUserDO!=null) {
                                famForumiIformRespVO.setNickName(memberUserDO.getNickname());
                                famForumiIformRespVO.setHeadPortrait(memberUserDO.getAvatar());
                            }
                        }
                    });
                }
            }
        }

        if (pageVO.getIsRead()!=null && pageVO.getIsRead()==1) {
            famForumiIformRespVOS=famForumiIformRespVOS.stream().
                    filter(item -> item.getIsRead() == 1)
                    .collect(Collectors.toList());
        }else if(pageVO.getIsRead()!=null && pageVO.getIsRead()==2) {
            famForumiIformRespVOS=famForumiIformRespVOS.stream().
                    filter(item -> item.getIsRead() == 2)
                    .collect(Collectors.toList());
        }

        if (famForumiIformRespVOS!=null) {
            famForumiIformRespVOS.forEach(famForumiIformRespVO -> {
                Long res = famForumRecordMapper.selecespeakType(famForumiIformRespVO.getForumId());
                if (res!=null) {
                    famForumiIformRespVO.setSpeakType(res);
                }
            });
            List<FamForumiIformRespVO> pageList = new ArrayList<>();
            int curIdx = pageVO.getPageNo() > 1 ? (pageVO.getPageNo() - 1) * pageVO.getPageNo() : 0;
            for (int i = 0; i < pageVO.getPageSize() && curIdx + i < famForumiIformRespVOS.size(); i++) {
                pageList.add(famForumiIformRespVOS.get(curIdx + i));
            }

//            IPage<FamForumiIformRespVO> page = new Page<>(); // 创建一个Page对象
            IPage page = new Page<>(pageVO.getPageNo(), pageVO.getPageSize());
//            page.setCurrent(pageVO.getPageNo()); // 设置当前页码
//            page.setSize(pageVO.getPageSize()); // 设置每页显示的数量
            page.setTotal(pageList.size()); // 设置总数，如果有其他分页条件可能需要动态计算
            page.setRecords(pageList); // 设置总数，如果有其他分页条件可能需要动态计算
            return page;
        }
        return null;
    }

    @Override
    public void getFamForumInformread(List<FamForumiIformRespVO> pageVO) {
        if (pageVO.size()>0) {
            for (int i = 0; i < pageVO.size(); i++) {
                FamForumiIformRespVO famForumiIformRespVO = pageVO.get(i);
                if (famForumiIformRespVO.getState()!=null || famForumiIformRespVO.getState()==1 || famForumiIformRespVO.getState()==2) {
                    //收藏/点赞 记录表
                    famForumRecordMapper.setrecord(famForumiIformRespVO.getId());
                }else {
                    //谈论回复表
                    famForumRecordMapper.setreply(famForumiIformRespVO.getId());
                }
            }
        }
    }

}
